package com.card.admin;

import org.jboss.netty.channel.ChannelHandlerContext;

import com.card.common.MessageComm;
import com.card.message.JsonMessageCenter;
import com.card.setting.GameSetting;
import com.xiaoao.net.config.ApplicationConfiguration;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.utils.PubFunc;
import com.xiaoao.net.utils.URLUtil;
import com.xiaoao.net.utils.json.GSONUtils;

public class IosServerManager {
	public static final boolean CheckV = ApplicationConfiguration.Properties().GetBoolean(
			IosServerManager.class, "CheckV");
	public static final String AppId = ApplicationConfiguration.Properties().GetString(
			IosServerManager.class, "AppId");
	public static final String Token = ApplicationConfiguration.Properties().GetString(
			IosServerManager.class, "Token");
	
	private static IosServerManager instance = new IosServerManager();
    public static IosServerManager getInstance() {
        return instance;
    }
    private UpgradeInfo upgradeInfo;
    
    public boolean checkLogin(int versionCode,ChannelHandlerContext ctx) {
//    	if(versionCode > 0 && upgradeInfo != null && upgradeInfo.getVersion()>0 && versionCode != upgradeInfo.getVersion()) {
//    		upgradeInfo.sendUpgradeMessage(ctx);
//    		return false;
//    	}
//    	if(!CheckV) {
//    		return true;
//    	}
    	UpgradeInfo info = upgradeInfo;
    	if(info != null) {
    		int apkVersion = PubFunc.parseInt(info.getVersion());
        	if(info != null
        			&& versionCode < apkVersion
        			) {
//        		info.sendUpgradeMessage(ctx);
        		boolean qiangzhi = versionCode < GameSetting.getInstance().getIosMinCode();
        		JsonMessage message = JsonMessage.createMessage(MessageComm.S2C_Upgrade_Info);
        		message.addProperty("androidXiazai", GameSetting.getInstance().getIosXiazai());
        		message.addProperty("iosXiazai", GameSetting.getInstance().getIosXiazai());
        		message.addProperty("info", info.getChangelog()==null?"":info.getChangelog());
        		message.addProperty("qiangzhi", qiangzhi);
        		JsonMessageCenter.getInstance().sendMessage(message, ctx);
        		return !qiangzhi;
        	}
    	}
    	return true;
    }
    
    public UpgradeInfo load() {
    	try {
    		if(AppId == null) {
    			return null;
    		}
    		String url = "http://api.fir.im/apps/latest/"+AppId+"?api_token="+Token;
    		String json = URLUtil.urlGet(url);
    		this.upgradeInfo = GSONUtils.FromJSONString(json, UpgradeInfo.class);
    		return upgradeInfo;
		} catch (Exception e) {
		}
    	return null;
    }

	public static void main(String[] args) {
		long now = System.currentTimeMillis();
		UpgradeInfo info = IosServerManager.getInstance().load();
		System.err.println("进行："+(System.currentTimeMillis()-now));
		System.err.println(PubFunc.parseInt(info.getVersion())>2);
		System.err.println(info.toString());
	}
}

